package tms;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Helper {

    /**
     * Parse integer from a string.
     * @param s string to parse
     * @return return -1 if input is NaN
     */
    public static int parseInt(String s) {
        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    /**
     * Parse double from a string.
     * @param s string to parse
     * @return return -1 if input is NaN
     */
    public static double parseDouble(String s) {
        try {
            return Double.parseDouble(s);
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    /**
     * Parse a date from a string.
     * @param strDate string to parse
     * @param format please use DbManager.DATE_FORMAT
     * @return a formatted date corresponding with the given pattern
     */
    public static Date parseDate(String strDate, String format) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.parse(strDate);
    }

    /**
     * Parse a string form a date.
     * @param date date to parse
     * @param format please use DbManager.DATE_FORMAT
     * @return a string corresponding with the given date and pattern
     */
    public static String dateToString(Date date, String format) {
        assert (date != null);

        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(date);
    }

    public static Date createDate(int day, int month, int year) {
        assert (day > 0 && month > 0 && year > 0);

        Calendar ca = Calendar.getInstance();
        ca.set(year, month - 1, day);
        return ca.getTime();
    }

    public static String hourMinToString(Date date) {

        Calendar ca = Calendar.getInstance();
        ca.setTime(date);

        return ca.get(Calendar.HOUR_OF_DAY) + "h " + ca.get(Calendar.MINUTE) + "m";
    }

    public static String getNowString(String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        return formatter.format(new Date());
    }
}
